//
//  JROAuthViewController.swift
//  myWeibo
//
//  Created by 樊健荣 on 16/7/19.
//  Copyright © 2016年 樊健荣. All rights reserved.
//

import UIKit
import SVProgressHUD
class JROAuthViewController: UIViewController {

    override func loadView() {
        self.view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置webView的代理
        webView.delegate = self
        
        
        //设置导航栏按键
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "remenber")
        
//        let urlString = ""
        
       let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)")
        let request = NSURLRequest(URL: url!)
        self.webView.loadRequest(request)
        
        
        
    }
    
    // MARK: - navi 按钮点击事件
    @objc private func cancel() {
        SVProgressHUD.dismiss()
        self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func remenber() {
    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value='13450257996';document.getElementById('passwd').value='q84923482'")
    }
    

    lazy var webView: UIWebView = UIWebView()

}

// MARK: - WebView代理事件
extension JROAuthViewController: UIWebViewDelegate {

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("\(request.URL!.absoluteString)")
        
        SVProgressHUD.showWithStatus("正在加载")
        
        //得到webView的重定向URLString
        let urlString = request.URL!.absoluteString
        if !urlString.hasPrefix("\(redirect_uri)"+"/") {
            return true
        }
        //可以进来这里面说明点击了取消或者授权按钮
        let codeString = "code="
        //?后面的字符
        let query = request.URL!.query!
        if query.hasPrefix(codeString) {
            //点击了授权按钮
            //截取code
            let queryNSSting = query as NSString
            //得到code
            let code = queryNSSting.substringFromIndex(codeString.characters.count)
            //采用抽取出去的ViewModel的网络请求方法
            JRAccountViewModel.sharedAccountViewModel.loadToken(code)
            
            //dismiss
            cancel()
            //切换控制器
            AppDelegate.switchRootViewController(JRWelcomeViewController())
            
            
        } else {
            //点击了取消按钮
            print("点击了取消按钮")
            cancel()
        }
        
        
        return false
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
}

